Compress Javascript and CSS Files Using PHP


Enhance your Javascript and CSS resources:

I have been doing some web applications lately, and wanted to compress my Javascript and CSS files so that page loads are quicker and also the files are cached at all times.

So i thought to myself, that we could truncate the JS and CSS files by removing the unwanted spaces and characters.

So i began writing a script that does the following:

  1. Reads JS or CSS files(s) from a particular folder called either js or css.
  2. Removes all the unwanted characters and blank spaces.
  3. Creates a new file in a new directory called js_cache or css_cache.
  4. Wallla!! we have done it, you have successfully reduced the file file size.

The script will allow you to manage easily your Javascript and CSS resources and to reduce the amount of data transferred between the server and the client.

Performances:

We can say that the performance is better but not the best, but it works.

You would see a slight reduce in time between the server and the client.

Restrictions:

In CSS files there are no problems, but in case of Javascript there may some problems where single line comments are used like ‘// comment ‘.

Therefore always use multi line comments like /* comment */ if you want to use this script

Requirements:

  1. Create a folder for you project
  2. Dump all the js files in js folder and css files in css folder
  3. Then create two more folders js_cache and css_cache
  4. Copy and paste this script in the project directory
  5. Edit the script by changing the constant FILE_TYPE as js or css only
  6. Run the script
  7. New files will be created in js_cache and css_cache
  8. Wow, its done now use these file instead of the original one

ALL THE BEST…

HAPPY SCRIPTING…..

Do keep sharing!!!

Download file:

Compress Javascript and CSS Files Using PHP

Leave a comment